import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { DataDropDown } from 'entities';
import { DataDictionaryService } from 'services';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    moduleId: module.id,
    selector: 'data-drop-down',
    templateUrl: 'data-drop-down.component.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DataDropDownComponent),
            multi: true
        },
        DataDictionaryService
    ]
})
export class DataDropDownComponent implements ControlValueAccessor, OnInit {

    @Input() width = '100%';
    @Input() groupCode: string;
    @Input() controlName: string;
    @Output() selectChange = new EventEmitter<DataDropDown>();
    onChangeListener; // 改变值回调
    onTouchedListener; // 交互回调
    isDisabled: boolean;
    selectCode: string;

    dataList: DataDropDown[] = [];
    constructor(private dictionaryService: DataDictionaryService) {

    }
    writeValue(obj: any): void {
        this.selectCode = obj;
    }
    registerOnChange(fn: any): void {
        this.onChangeListener = fn;
    }
    registerOnTouched(fn: any): void {
        this.onTouchedListener = fn;
    }
    setDisabledState?(isDisabled: boolean): void {
        this.isDisabled = isDisabled;
    }
    ngOnInit(): void {
        this.getDataList();
    }

    getDataList() {
        this.dictionaryService.getDataGroupList(this.groupCode).subscribe(result => {
            this.dataList = result;
            if (this.selectCode) {
                this.selectData(this.selectCode);
            }
        });
    }

    selectData(code: any) {
        if (this.onChangeListener) {
            this.onChangeListener(code); // 告诉form，你的表单值改变成了
        }
        if (this.onTouchedListener) {
            this.onTouchedListener(); // 告诉form，你的表单有交互发生
        }
        const data = this.dataList.find(d => d.code == code);
        this.selectChange.emit(data);
    }
}
